/*! phonebar v1.0.0 | (c) created 20190327 | hejm@huayunworld.com */
 var webPhoneVersion = '2.1.1'; // 2022-3-15 
 console.log('webphone-version:', webPhoneVersion);
//  var baseUrl = './static/newPhone_web/';
 var baseUrl = './static/hyPhone/';
 var testHost = './';
 //var testHost = 'http://62.234.92.196/';
var acwTimer = null;
require.config({
    baseUrl : baseUrl+"js",
    paths : {
        "jquery" : ["jquery"],
        "uc" : ["uc"],
        "jquery.md5": ["jquery.md5"]
    }
})
    define(["jquery","uc","jquery.md5"],function($,AgentBar) {
        // 引jquery
        // 验证是否引用jquery
        // if (!$ || !$.fn || !$.fn.jquery) {
        //     alert('在引用之前，先引用jQuery，否则无法使用');
        //     return;
        // }
        // 兼容
        if (typeof Object.assign !== 'function') {
            Object.assign = function(target) {
                'use strict';
                if (target == null) {
                    throw new TypeError('Cannot convert undefined or null to object');
                }

                target = Object(target);
                for (var index = 1; index < arguments.length; index++) {
                    var source = arguments[index];
                    if (source != null) {
                        for (var key in source) {
                            if (Object.prototype.hasOwnProperty.call(source, key)) {
                                target[key] = source[key];
                            }
                        }
                    }
                }
                return target;
            };
        }
        if (!Array.prototype.find) {
            Array.prototype.find = function(predicate) {
                'use strict';
                if (this == null) {
                    throw new TypeError('Array.prototype.find called on null or undefined');
                }
                if (typeof predicate !== 'function') {
                    throw new TypeError('predicate must be a function');
                }
                var list = Object(this);
                var length = list.length >>> 0;
                var thisArg = arguments[1];
                var value;

                for (var i = 0; i < length; i++) {
                    value = list[i];
                    if (predicate.call(thisArg, value, i, list)) {
                        return value;
                    }
                }
                return undefined;
            };
        }
        if (!Array.indexOf) {
            Array.prototype.indexOf = function (obj) {
                for(var i = 0;i < this.length;i++){
                    if (this[i] == obj) {
                        return i;
                    }
                }
                return -1;
            }
        }
        var timeFormat = function (timeCode, format) {
            var year = timeCode.getFullYear();
            var month = timeCode.getMonth() + 1;
            var strDate = timeCode.getDate();
            var hour = timeCode.getHours();
            var minutes = timeCode.getMinutes();
            var second = timeCode.getSeconds();
            var timeFormat;
            if (format === null || format === undefined) {
                timeFormat= year + '-' + month + '-' + strDate + ' ' + hour + ':' + minutes + ':' + second;
            } else if (format.toLowerCase() === 'hh:mm:ss'){
                timeFormat= hour + ':' + minutes + ':' + second;
            } else if (format.toLowerCase() === 'yyyy-mm-dd') {
                timeFormat = year + '/' + month + '/' + strDate;
            }
            return timeFormat;
        }
        // 最小化无法播放声音的其他方式提醒-------
        function getHiddenProp() {
            var prefixes = ['webkit','moz','ms','o'];
            // if 'hidden' is natively supported just return it
            if ('hidden' in document) return 'hidden';
            // otherwise loop over all the known prefixes until we find one
            for (var i = 0; i < prefixes.length; i++)
            {
              if ((prefixes[i] + 'Hidden') in document)
                return prefixes[i] + 'Hidden';
            }
            return null;
        }
        function startMessTwinkle() { // 消息闪烁
            let flag = false;
            window.twinkleTime = setInterval(function() {
              flag = !flag;
              document.title = flag ? '【有新电话】' : '【    】';
            }, 100)
            let visProp = getHiddenProp();
            if (visProp) {
                let evtname = visProp.replace(/[H|h]idden/, '') + 'visibilitychange';
                document.addEventListener(evtname, function () {
                if (document[getVisibilityState()] === 'visible') {
                    if (window.twinkleTime) {
                    clearInterval(window.twinkleTime);
                    window.twinkleTime = null;
                    }
                    document.title = window.projectRelative.title;
                }
                }, false);
            }
        }
        function isHidden() {
            var prop = getHiddenProp();
            if (!prop) return false;
            
            return document[prop];
        }
        function showNotice(messageTitle, messageIcon, messageContent) {
            if (typeof Notification !== 'undefined') {
              Notification.requestPermission(function (perm) {
                if (perm === 'granted') {
                  var notification = new Notification(messageTitle, {
                    icon: messageIcon,
                    requireInteraction: false,
                    body: messageContent
                  });
                  var timeout = setTimeout(function () {
                    notification.close();
                    clearTimeout(timeout);
                  }, 5000);
                  notification.onclick = function () {
                    window.focus();
                  }
                } else {
                  console.log('denied');
                }
              })
            }
        }
        function checkIsHiddenCalled(number) {
            let aaasdf = isHidden();
            if (aaasdf) {
                var messageTitle = '新电话';
                var messageIcon = './static/images/zhongyaotixing.png';
                var messageContent = '有新电话！';
                showNotice(messageTitle, messageIcon, messageContent);
            }
            console.log('打印定时----浏览器状态-----', aaasdf)
        }
        function autoplayFirstMute() {
            console.log('=========登录时候的connected----');
            var local_audio_src = baseUrl + '/utils/mute.mp3';
            var localAudio = document.getElementById('audio_local');
            localAudio.src = local_audio_src;
            localAudio.paused && (localAudio.play());
            console.log('=========登录时候的connected----', localAudio);
        }
        // 最小化无法播放声音的其他方式提醒=========
        // 引require
        // 定义扩展函数
        var _p = function (fn) {
            var P = window.newPhone;
            if (P) {
                // 执行传入的函数
                fn(P, $);
            }
        };
        /*
        * 电话条整体构造函数
        */
        (function(window, $) {
            if (window.newPhone) {
                // 重复引用
                alert('一个页面不能重复引用 phone.js 或 phone.min.js ！！！');
                return;
            }
            //（整体）构造函数
            var P = function (elem) {
                // ------------------初始化------------------
                this.initDefaultConfig();
            };
            P.fn = P.prototype;
            P.$body = $('body');
            P.$document = $(document);
            P.$window = $(window);
            P.userAgent = navigator.userAgent;
            P.getComputedStyle = window.getComputedStyle;
            // P.UCObj = UCObj;
            //P.uc304 = uc304;
            //P.uc305 = uc305;
            P.AgentBar = AgentBar;
            // 暴露给全局对象
            window.newPhone = P;
        })(window, $);
        /*
        * 电话状态定义
        */
        _p(function(P, $){
            var EventStatus = function(btn_login, btn_logout, btn_ready, btn_notready, btn_answer, btn_disconnect, btn_callout, btn_holdon, btn_consult,btn_transfer, btn_callback, btn_meet, btn_monitor, btn_insert, btn_drop, btn_reset, btn_set, btn_cooperation,btn_transferIvr,btn_assistService,btn_reconnectCall,btn_singleStep) {
                this.btn_login = btn_login;   //登入 1
                this.btn_logout = btn_logout; //登出 2
                this.btn_ready = btn_ready; //置闲 3
                this.btn_notready = btn_notready; //置忙 4
                this.btn_answer = btn_answer; //接听 5
                this.btn_disconnect = btn_disconnect; //挂断 6
                this.btn_callout = btn_callout; //外呼 7
                this.btn_holdon = btn_holdon;  //保持 8
                this.btn_consult = btn_consult; //咨询 9
                this.btn_transfer = btn_transfer;  //转接 10
                this.btn_callback = btn_callback;  //接回 11
                this.btn_meet = btn_meet; //会议 12
                this.btn_monitor = btn_monitor; //监听 13
                this.btn_insert = btn_insert; //强插 14
                this.btn_drop = btn_drop;  //强拆 15
                this.btn_reset = btn_reset;  //重置 16
                this.btn_set = btn_set; //设置 17
                this.btn_cooperation = btn_cooperation; //协作 18
                this.btn_transferIvr = btn_transferIvr; //转IVR 19
                this.btn_assistService = btn_assistService; //密语 20
                this.btn_reconnectCall = btn_reconnectCall; //咨询接回 21
                this.btn_singleStep = btn_singleStep;// 单步 转接、会议 22
            }
            P.EventStatus = EventStatus;
        })
        /*
        * 全局配置
        */
        _p(function(P, $) {
            P.config = {};
            // 默认 菜单配置
            P.config.menus  = [
                'btn_login',
                'btn_logout',
                'btn_ready',
                'btn_notready',
                'btn_answer',
                'btn_disconnect',
                'btn_callout',
                'btn_holdon',
                'btn_consult',
                'btn_transfer',
                'btn_callback',
                'btn_meet',
                'btn_monitor',
                'btn_insert',
                'btn_drop',
                'btn_reset',
                'btn_set',
                'btn_cooperation', // 坐席协作
                'btn_transferIvr', //转IVR
                'btn_assistService', //密语
                'btn_reconnectCall', //咨询接回
                'btn_singleStep' // 单步 转接、会议
            ];
            P.config.httpServerAddress = ''
            P.config.stateList = {
                AgentStatus_Init: 'Init',
                AgentStatus_Login: '置忙',
                AgentStatus_Logout: '未登录',
                AgentStatus_NotReady: '置忙',
                AgentStatus_Ready: '置闲',
                AgentStatus_Otherwork: '置忙',
                AgentStatus_ACW: '整理',
                AgentStatus_Locked: '锁定中',
                AgentStatus_Alerting: '振铃中',
                AgentStatus_Connecting: '振铃中',
                AgentStatus_Connected_Normal: '通话中',
                AgentStatus_Connected_Internal: '通话中',
                AgentStatus_Disconnected: null,
                AgentStatus_Suspended: '保持中',
                AgentStatus_Held: '保持中',
                AgentStatus_Consulting: '振铃中', // 咨询振铃中
                AgentStatus_Consulted: '咨询中',
                AgentStatus_Conferenced: '会议中',
                AgentStatus_Monitored: '监听中',
                AgentStatus_Inserted: '通话中',
                AgentStatus_Unkown: 'unknown',
            }
            P.config.eventList = {
                AgentStatus_Init: new P.EventStatus(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
                AgentStatus_Login: new P.EventStatus(0,1,1,0,0,0,1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0), //可外呼
                AgentStatus_Logout: new P.EventStatus(1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
                AgentStatus_NotReady: new P.EventStatus(0,1,1,0,0,0,1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0), //可外呼
                AgentStatus_Ready: new P.EventStatus(0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0),
                AgentStatus_Otherwork: new P.EventStatus(0,1,1,1,0,0,1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0), // 可外呼 可监听
                AgentStatus_ACW: new P.EventStatus(0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0), // 不可外呼
                AgentStatus_Locked: new P.EventStatus(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0), // 不需要
                AgentStatus_Alerting: new P.EventStatus (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0),
                AgentStatus_Connecting: new P.EventStatus(0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0),
                AgentStatus_Connected_Normal: new P.EventStatus(0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,1,1,0,0,1),
                AgentStatus_Connected_Internal: new P.EventStatus(0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,1), // 内部咨询通话/将转接和会议置0/2022-4-1tyy修改
                AgentStatus_Disconnected: new P.EventStatus(0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0),
                AgentStatus_Suspended: new P.EventStatus(0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0),//这里采用了接回的样式,原本全是0
                AgentStatus_Held: new P.EventStatus(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0),
                AgentStatus_Consulting: new P.EventStatus(0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0), // 向对方咨询-咨询接回21置1，挂断??置1/2022-4-1tyy修改
                AgentStatus_Consulted: new P.EventStatus(0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0),// 将保持置为0/-2022-4-1tyy修改
                AgentStatus_Conferenced: new P.EventStatus(0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0),
                AgentStatus_Monitored: new P.EventStatus(0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0,0),
                AgentStatus_Inserted: new P.EventStatus(0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
                AgentStatus_Unkown: new P.EventStatus(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0),
                AgentStatus_noAnswer: new P.EventStatus(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0)
            }
            P.config.stateDescription = {}
            P.config.autoReadyKey = ''
            P.config.acwTimerKey = 0
        })
        /*
        * 对象配置
        */
        _p(function(P, $) {
            P.fn.initDefaultConfig = function () {
                var phone = this;
                // 将 config 配置参数 定义到具体对象上
                phone.config = $.extend({}, P.config);
                // 电话条 初始化 及 登录参数
                phone.loginConfig = {};
                // 是否初始化成功参数
                //phone.initializeState = false;
                phone.initializeState = true;
                // 初始化菜单集合
                phone.menus = {};
                //回调状态保存
                phone.EventType = '';
                //将要获取的回调状态保存
                phone.toEventType = '';
                phone.renderEvents = {};
            };
        })
        /*
        * 电话条切换小状态按钮
        */
        _p(function(P, $){
            P.fn.changeSmallStatus = function (status, render) {
                var phone = this;
                if(window.isautoLoginFlag) {
                    var changeSmallStatusUrl = phone.config.httpServerAddress + '/smallStatus/smallStatus/api/getSmallStatus?entId='+window.phoneUserInfo.entId+'&agentId='+window.phoneUserInfo.agentID+'&agentPwd='+window.phoneUserInfo.password.toUpperCase()+'&status='+status+'&operaTime='+ timeFormat(new Date());
                } else{
                    var changeSmallStatusUrl = phone.config.httpServerAddress + '/smallStatus/smallStatus/api/getSmallStatus?entId='+window.phoneUserInfo.entId+'&agentId='+window.phoneUserInfo.agentID+'&agentPwd='+$.md5(window.phoneUserInfo.password).toUpperCase()+'&status='+status+'&operaTime='+ timeFormat(new Date());
                }
                $.ajax({
                    url: changeSmallStatusUrl,
                    dataType: 'jsonp',
                    type: "GET",
                    success: function(res) {
                        // 修改小状态的样式
                        render(res);
                    }
                })
            }
        })
        /*
        * 电话条登录事件
        */
        _p(function(P, $) {
            P.fn.login = function() {
                var phone = this;
                // 需要取到登录时的地址
                phone.loginConfig = window.phoneUserInfo;
                var LoginURL = window.phoneUserInfo.httpServerAddress;
                var agentId = window.phoneUserInfo.agentID;
                var password = window.phoneUserInfo.password;
                var EnterpriseID = window.phoneUserInfo.entId;
                var agentDN = window.phoneUserInfo.sipUser;
                var TerminalType = window.phoneUserInfo.TerminalType;
                var skillDesc = window.phoneUserInfo.skillDesc;
                phone.renderEvents.loginingRender();
                // var newPassword = $.md5(password).toUpperCase();
                console.log('pwdddd----', window.isautoLoginFlag)
                if(window.isautoLoginFlag) {
                    var newPassword = password.toUpperCase();
                } else {
                    var newPassword = $.md5(password).toUpperCase();
                }
                console.log('pwdddd---123-', newPassword)
                phone.config.httpServerAddress = LoginURL;
                var  proxyUrl = LoginURL;
                phone.ucObj = new P.AgentBar(P.$window[0], P.$document[0]);

                var agentDnPwd = window.phoneUserInfo.agentDnPwd;
                var serverUrl  = window.phoneUserInfo.serverUrl;
                var wsUrl  = window.phoneUserInfo.wsUrl;
                var udpUrl = window.phoneUserInfo.udpUrl;
                var stunServers = window.phoneUserInfo.stunServers;

                phone.ucObj.initUCObj(agentId, newPassword,EnterpriseID,agentDN, agentId,TerminalType,skillDesc,proxyUrl,agentDnPwd,serverUrl,wsUrl,udpUrl,stunServers);
                if (window.phoneUserInfo.channel && window.phoneUserInfo.channel === 'external') {
                   // 外部接入目前不做处理
                   console.log('外部渠道接入');
                } else {
                    $('.phonebar').width("520");
                    $('.pho-chongzhi').height("290");
                    console.log('ss登录getBtnState 电话条宽度', $('.phonebar').width());
                    setTimeout(()=>{
                        getBtnState();
                    },1000)
                }

                // 判断是否已登陆
                phone.ucObj.GetAgentState(agentId, function (res) {
                    console.log("res" + JSON.stringify(res));
                    if (res.Code === '0') {
                        // 需要查询的是当前坐席 而且是当前坐席已经是登录状态
                        if ((res.IsLogon === true && res.EntId === EnterpriseID && res.AgentId === agentId) && res.AgentStatus !== 'AgentStatus_Logout') {
                            // 恢复初始化状态
                            loginCallBack({Code: '0'});
                            phone.getEventStatus(res.Event, res.AgentStateTime);
                        } else {
                            // 发起请求
                            phone.ucObj.loginex(loginCallBack.bind(phone));
                        }
                    }
                });
                function getBtnState() { // 控制电话条上按钮是否显示
                    console.log('ss登录getBtnState', $('.pho-chongzhi').height())
                    console.log($('.phonebar'), 111)
                    $('.phonebar').width("520")
                    $('.pho-state-change').hide()
                    console.log('ss登录getBtnState phonebar width-42--btn_holdon', $('.phoarraybox .btn_holdon'))
                    $.ajax({
                    url: 'cca/agentInfo/getCallCenterInfo',
                    type: 'GET',
                    // dataType: "jsonp",
                    // jsonp: "callback",
                    success: function (data) {
                        $('.phonebar').width("520"); // 恢复电话条初始宽度
                        if (data.code === 0) {
                        phone.btnStatus = data.status;    
                        if (phone.btnStatus["101"] === "0") {
                            $('.btn_holdon').hide() // 隐藏保持按钮
                            // $('.phonebar').width($('.phonebar').width() - 42);
                        } else {
                            $('.phonebar').width($('.phonebar').width() + 42);
                            $('.btn_holdon').show()
                        }
                        if (phone.btnStatus["102"] === "0") {
                            $('.btn_consult').hide() // 隐藏咨询按钮
                            // $('.phonebar').width($('.phonebar').width() - 42);
                        } else {
                            $('.phonebar').width($('.phonebar').width() + 42);
                            $('.btn_consult').show()
                        }
                        if (phone.btnStatus["103"] === "0") {
                            $('.btn_transfer').hide() // 隐藏转接按钮
                            // $('.phonebar').width($('.phonebar').width() - 42);
                        } else {
                            $('.phonebar').width($('.phonebar').width() + 42);
                            $('.btn_transfer').show()
                        }
                        if (phone.btnStatus["104"] === "0") {
                            $('.btn_meet').hide() // 隐藏会议按钮
                            // $('.phonebar').width($('.phonebar').width() - 42);
                        } else {
                            $('.phonebar').width($('.phonebar').width() + 42);
                            $('.btn_meet').show()
                        }
                        if (phone.btnStatus["200"] === "0") {
                            let a = $('.phonebar').width()
                            $('.btn_monitor').hide(); // 隐藏监听按钮
                            // $('.phonebar').width($('.phonebar').width() - 42);
                        } else {
                            $('.phonebar').width($('.phonebar').width() + 42);
                            $('.btn_monitor').show()
                        }
                        if (phone.btnStatus["201"] === "0") {
                            $('.btn_drop').hide() // 隐藏强拆按钮
                            // $('.phonebar').width($('.phonebar').width() - 42);
                        } else {
                            $('.phonebar').width($('.phonebar').width() + 42);
                            $('.btn_drop').show()
                        }
                        if (phone.btnStatus["202"] === "0") {
                            $('.btn_insert').hide() // 隐藏强插按钮
                            // $('.phonebar').width($('.phonebar').width() - 42);
                        } else {
                            $('.phonebar').width($('.phonebar').width() + 42);
                            $('.btn_insert').show()
                        }
                        if (phone.btnStatus["203"] === "0" ) {
                            $('.pho-chongzhi>.btn_assistService').hide() // 隐藏密语按钮
                            $('.pho-chongzhi').height($('.pho-chongzhi').height() - 36);
                        } else {
                            $('.pho-chongzhi.btn_assistService').show()
                        }
                        if (phone.btnStatus["109"] === "0") {
                            $('.pho-chongzhi>.btn_cooperation').hide() // 隐藏协作按钮
                            $('.pho-chongzhi').height($('.pho-chongzhi').height() - 36);
                        } else {
                            $('.pho-chongzhi>.btn_cooperation').show()
                        }
                        if (phone.btnStatus["110"] === "0" ) {
                            $('.pho-chongzhi>.btn_transferIvr').hide() // 隐藏转IVR按钮
                            $('.pho-chongzhi').height($('.pho-chongzhi').height() - 36);
                        } else {
                            $('.pho-chongzhi>.btn_transferIvr').show()
                        }
                        // if (phone.btnStatus["111"] === "0" ) {
                        //     $('.btn_degree').hide() // 隐藏满意度按钮
                        //     $('.phonebar').width($('.phonebar').width() - 45);
                        // }
                        // if (phone.btnStatus["112"] === "0" ) {
                        //     $('.btn_transferSkill').hide() // 隐藏转技能组按钮
                        //     $('.phonebar').width($('.phonebar').width() - 60);
                        // }
                        // if (phone.btnStatus["113"] === "0" ) {
                        //     $('.btn_startmute').hide() // 隐藏静音按钮
                        //     $('.phonebar').width($('.phonebar').width() - 60);
                        // }
                        //   $('.phonebar').width($('.phonebar').width() + 42);
                        console.log($('.phonebar').width(), 111)

                        }
                    },
                    error: function () {
                        console.log('ss登录error');
                        $('.phonebar').width('860');
                        $('.pho-state-change').show();
                        $('.phonebar>.btn_assistService').hide(); // 隐藏密语按钮
                        $('.phonebar>.btn_cooperation').hide(); // 隐藏协作按钮
                        $('.phonebar>.btn_transferIvr').hide(); // 隐藏转IVR按钮
                    }
                    })
                }
                function loginCallBack(data) {
                    console.log("loginCallBack----登录--" + JSON.stringify(data));
                    if (data.Code === '0') {
                        phone.renderEvents.loginRender(data);
                        // 开始轮询
                        phone.ucObj.start(phone.getEventStatus.bind(phone));
                        // 查询外显号码(可能获取到多个)
                         phone.ucObj.doGetShowANI(function(data) {
                         if (data.Code === '0') {
                         //将外显号码曝出
                            phone.renderEvents.explicitNumRender(data['Msg']);
                           }
                         })
                        //  获取 电话条 小状态内容
                        $.ajax({
                            url:   phone.config.httpServerAddress + '/smallStatus/smallStatus/api/querySmallStatusTypeByEntId?entId=' + window.phoneUserInfo.entId+"&callback=?",
                            type: "GET",
                            dataType: "jsonp",
                            jsonp: "callback",
                            success: function (res) {
                                if (res.status === '0' && res.data.length > 0) {
                                    phone.smallStatus = res.data;
                                }
                                /*else {
                                 phone.smallStatus = '置忙'
                                 }*/
                                phone.renderEvents.smallStatusRender(phone.smallStatus);
                            },
                            error: function () {
                                //phone.smallStatus = '置忙';
                                phone.renderEvents.smallStatusRender(phone.smallStatus);
                            }
                        })
                        /* phone.smallStatus =[{"statusCode":1,"statusName":'小休'}];
                         phone.renderEvents.smallStatusRender( phone.smallStatus);*/
                    } else {
                        phone.renderEvents.loginRender(data)
                    }
                }



            }
        })
        /*
        *电话条登出事件
         */
        _p(function(P, $){
            P.fn.logout = function() {
                var phone = this;
                if (phone.ucObj) {
                  phone.ucObj.doLogOut(function(data) {
                    phone.renderEvents.logoutRender();
                    if (data.Code === '0') {
                      //phone.ucObj.stopObj();
                    }
                  });
                } else {
                  phone.renderEvents.logoutRender();
                }
            }
        })
        /*
        * menu 构造函数
        */
        _p(function (P, $) {
            // 定义构造函数
            var Menu = function (opt) {
                this.phone = opt.phone;
                this.menuId = opt.id;
            };
            P.Menu = Menu;
        });
        /*
        * 菜单事件
        */
        _p(function (P, $) {
            var createMenuFn = [];
            P.createMenu = function(fn) {
                createMenuFn.push(fn);
            };
            P.fn.defineEvent = function(menuId,obj) {
                var phone = this;
                if (obj === undefined) {
                    phone.menus[menuId].clickEvent();
                } else if(obj.hasOwnProperty('callNum')){ // 外拨传参
                    // phone.menus[menuId].clickEvent(obj['callNum'], obj['showNum']);
                    console.log('外呼外呼-111', phone.menus[menuId], phone.EventType)
                    if (phone.EventType === 'AgentStatus_Ready') { // 置闲外呼
                        // 置忙
                        phone.defineEvent('btn_notready');
                        setTimeout(function() {
                            console.log('外呼外呼-----1100')
                            phone.menus[menuId].clickEvent(obj['callNum'], obj['showNum']);
                        }, 1100)
                    } else { // 非置闲外呼
                        phone.menus[menuId].clickEvent(obj['callNum'], obj['showNum']);
                    }
                } else if (obj.hasOwnProperty('consultType') && obj.hasOwnProperty('targetNum')) { // 咨询传参
                    phone.menus[menuId].clickEvent(obj['consultType'], obj['targetNum']);
                } else if (obj.hasOwnProperty('conferenceParty')) { //监听传参
                    phone.menus[menuId].clickEvent(obj['conferenceParty']);
                }else if (obj.hasOwnProperty('destType')) { //监听传参
                    phone.menus[menuId].clickEvent(obj['destType']);
                }else if (obj.hasOwnProperty('consultTypeId') && obj.hasOwnProperty('destId')&& obj.hasOwnProperty('targetNumber')) { // 单步传参
                    phone.menus[menuId].clickEvent(obj['consultTypeId'],obj['destId'],obj['targetNumber']);
                }else if (obj.hasOwnProperty('destAgentID')) { // 强拆传参
                    phone.menus[menuId].clickEvent(obj['destAgentID']);
                }
                /*else if (obj.hasOwnProperty('destType') && obj.hasOwnProperty('destDesc')&& obj.hasOwnProperty('meetType')) { // 会议传参
                    phone.menus[menuId].clickEvent(obj['destType'], obj['destDesc'], obj['meetType']);
                }else if (obj.hasOwnProperty('callType') && obj.hasOwnProperty('transferNum')&& obj.hasOwnProperty('transferType')) { // 转接传参
                    phone.menus[menuId].clickEvent(obj['callType'], obj['transferNum'], obj['transferType']);
                }*/
            }
            // 添加菜单
            P.fn.addAllMenus = function() {
                var phone = this;
                var menuIds = phone.config.menus;

                // 检验 menuId 是否在配置中存在
                function check(menuId) {
                    if (menuIds.indexOf(menuId) >= 0) {
                        return true;
                    }
                    return false;
                }
                $.each(createMenuFn, function(k, fn) {
                    fn.call(phone, check);  // 改变this指向，同时传入参数check
                })
            }
        });
        /*
        * 登入菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_login';
                if (!check(menuId)) {
                    return;
                }
                var phone = this;
                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var initStatus = phone.initializeState;
                    if(initStatus && phone.toEventType !== 'AgentStatus_Login') {
                        //需要初始化成功 同时 按钮状态可点
                        phone.login();
                    }
                    phone.toEventType = 'AgentStatus_Login'
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 登出菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_logout';
                if (!check(menuId)) {
                    return;
                }
                var phone = this;
                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    if (phone.EventType === '') {
                        phone.toEventType = '';
                        phone.logout();
                        return;
                    }
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    // 登录失败  phone.EventType 是 空字符串
                    if (btnStatus && phone.toEventType !== 'AgentStatus_Logout') {
                        phone.logout();
                    }
                    phone.toEventType = 'AgentStatus_Logout'
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 置闲菜单
      */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_ready';
                if (!check(menuId)) {
                    return;
                }
                var phone = this;
                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    // 查看状态 可点的情况下，执行置闲
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];

                    if(btnStatus && phone.toEventType !== 'AgentStatus_Ready') {
                        phone.ucObj.doReady();
                    };
                    phone.toEventType = 'AgentStatus_Ready';
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 置忙菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_notready';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];

                    if(btnStatus && phone.toEventType !== 'AgentStatus_NotReady') {
                        phone.ucObj.doNotReady();
                    }
                    phone.toEventType = 'AgentStatus_NotReady'
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 接听菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_answer';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    // 有可能是两种  正常接通/咨询接通（AgentStatus_Consulted）
                    phone.toEventType = 'AgentStatus_Connected_Normal'
                    if(btnStatus) {
                        phone.ucObj.doAnswer();
                    }
                    if (phone.toEventType !== phone.EventType || 'AgentStatus_Consulted' !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 挂断菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_disconnect';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    console.log('调用phone.js-中的1btn_disconnect')
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    // AgentStatus_ACW(事后整理) AgentStatus_Disconnected 两个状态一起返回
                    phone.toEventType = 'AgentStatus_ACW' + 'AgentStatus_Disconnected';
                    if(btnStatus) {
                        console.log('调用phone.js-中的2btn_disconnect')
                        phone.ucObj.doDisconnect();
                    }
                    // if (phone.toEventType !== phone.EventType) {
                    if (phone.toEventType.indexOf(phone.EventType) === -1) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 外呼菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_callout';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function(callNum, showNum) {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Alerting'
                    console.log('=============外呼外呼--------', callNum, callNum.trim(), '***', showNum);
                    callNum = callNum.trim();
                    console.log('=============外呼外呼-----------', callNum + '&', '***', showNum);
                    if(btnStatus) {
                        // 收到 Alerting振铃事件 才能去调 doAnswer
                        var showNum = phone.config.explicitNum;
                        if(null!=showNum && showNum!='' && typeof(showNum)!='undefined'){

                            showNum = 'tel:' +showNum;
                        }
                        phone.ucObj.doCallOut(callNum, showNum);
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 客户被保持保持菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_holdon';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Suspended'
                    if(btnStatus) {
                        phone.ucObj.doHold();
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 接回菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_callback';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Connected_Normal'
                    if(btnStatus) {
                        phone.ucObj.doRetrive();
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 咨询菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_consult';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function(consultType, targetNum) {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Consulting';
                    if(btnStatus) {
                        phone.ucObj.doConsulting(consultType, targetNum);
                    }
                    setTimeout(function() {
                        console.log('点击咨询咨询---', phone)
                        if(phone && phone.agentZiXunBtnResponse && phone.agentZiXunBtnResponse.code == 200) {
                            phone.customgetStateFn(phone.config.eventList['AgentStatus_Consulting']);
                        }
                    }, 150)
                    /*
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                    */
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });


        /*
         * 咨询接回菜单
         */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_reconnectCall';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Connected_Normal';
                    phone.ucObj.reconnectCall();
                    //if(btnStatus) {
                    //    phone.ucObj.reconnectCall();
                    //}
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });

        /*
        * 转接菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_transfer';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Disconnected'
                    if(btnStatus) {
                        phone.ucObj.doAdressShift();
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });

        /*
       * 单步 转接 会议菜单
       */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_singleStep';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function(consultType,destId, targetNum) {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Suspended'
                    if(btnStatus) {
                        phone.ucObj.doSingleStep(consultType,destId, targetNum);
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });

        /*
        * 会议菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_meet';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Conferenced';
                    if(btnStatus) {
                        //会议
                        phone.ucObj.doMeeting();

                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 监听菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_monitor';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function(conferenceParty) {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Monitored'
                    if(btnStatus) {
                        phone.ucObj.doListen(conferenceParty);
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 强拆菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_drop';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function(destAgentId) {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_droped'
                    if(btnStatus) {
                        phone.ucObj.doDrop(destAgentId);
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 强插菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_insert';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Inserted'
                    if(btnStatus) {
                        phone.ucObj.doInsert();
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 座席协作
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_cooperation';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                   phone.toEventType = 'AgentStatus_ACW'
                    if(btnStatus) {
                        phone.ucObj.doAssistService("","");
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });


        /*
        * 坐席转IVR
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_transferIvr';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_ACW'
                    if(btnStatus) {
                        phone.ucObj.doTransferIVR();
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });


        /*
        * 监听密语
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_assistService';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function(destType) {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Monitored'
                    if(btnStatus) {
                        phone.ucObj.doWhisper(destType,function(data) {
                            if(data.code === '200' || data.code === 200){
                                var $assistService = $('.pho-state-change>.font10'); //
                                if(destType==1){
                                    $($assistService).text('结束');
                                }else  if(destType==2){
                                    $($assistService).text('密语');
                                }

                            }else{
                                alert(data.msg);
                            }
                        });
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
         * 坐席转自助
         */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_self_help';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_ACW'
                    if(btnStatus) {
                        phone.ucObj.doSelfHelp();
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });

        /*
        * 重置菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_reset';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    phone.toEventType = 'AgentStatus_Otherwork'
                    if(btnStatus) {
                        phone.ucObj.doReset();
                    }
                    if (phone.toEventType !== phone.EventType) {
                        // 状态没有返回 所有按钮将不能点
                        phone.customgetStateFn(phone.config.eventList['AgentStatus_noAnswer'])
                    }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 设置菜单
        */
        _p(function (P, $) {
            P.createMenu(function (check) {
                var menuId = 'btn_set';
                if (!check(menuId)) {
                    return;
                }

                var phone = this;

                // 创建 menu 对象
                var menu = new P.Menu({
                    phone: phone,
                    id: menuId
                });
                menu.clickEvent = function() {
                    var btnStatus = phone.config.eventList[phone.EventType][menuId];
                    // phone.toEventType = 'AgentStatus_ACW'
                    if(btnStatus) {
                        // phone.ucObj.doAnswer();
                    }
                    // if (phone.toEventType !== phone.EventType) {
                    //     // 状态没有返回 所有按钮将不能点
                    //     phone.customgetStateFn(phone.config.eventList['AgentStatus_Unkown'])
                    // }
                }
                // 增加到editor对象中
                phone.menus[menuId] = menu;
            });
        });
        /*
        * 轮询回调处理
        */
        _p(function(P) {
            // 处理状态文字显示
            function getStateTxt(EventType, CallDetailEvent) {
                var phone = this;
                var stateTxt = null;
                if (EventType === 'AgentStatus_Disconnected') return;
                stateTxt = phone.config.stateList[EventType];
                if (CallDetailEvent === 'CA_CALL_EVENT_OUTBOUND_CONNECTED_TP') { // 外呼本方接通
                    stateTxt = '振铃中'
                } else if (CallDetailEvent === 'CA_CALL_EVENT_OUTBOUND_CONNECTED_OP') { // 外呼对方接通
                    stateTxt = '通话中'
                }
                return stateTxt;
            }
            P.fn.getEventStatus = function(data, AgentStateTime) {
                var phone = this;
                var EventType = data.EventType;
                var CallDetailEvent = data.CallDetailEvent;
                console.log('web--phone接收uc的-事件', data)
                console.log('web--phone接收uc的-事222222件', $('.unknownTip'), '+++++++++++')
                // 各种响应error处理-
                if (data && data.MessageID == 'Resp_IContact_AgentLogin') {
                    if (data.code != 200) {
                        // $('.loginfail').text('电话条登录失败').show();
                        // 登陆失败渲染
                        $('.unknownTip').show(500, function() {
                            $('.unknownTip').find('p').text(data.msg);
                            $('.phonebarstate>p').text('未登录');
                        });
                    }
                }
                // 网络断开的error提示/sipml连接失败error
                if (data.Key_IContact_ErrorCode && data.Key_IContact_ErrorMsg && (phone.EventType !== 'AgentStatus_Logout')) {
                    console.log('errororor---', phone)
                    $('.unknownTip').show(500, function() {
                        var socketError = data.Key_IContact_ErrorMsg;
                        $('.unknownTip').addClass('sipmlError');
                        $('.unknownTip').find('p').text(socketError);
                    });
                }
                // 咨询错误
                if(data && data.MessageID == 'Resp_IContact_ConsultCall') {
                    console.log('phonejs的咨询--', data, phone.agentCurrentCalled);
                    phone.agentZiXunBtnResponse = data;
                    // 咨询失败渲染
                    if(data.code != 200) {
                        $('.unknownTip').show(500, function() {
                            $('.unknownTip').find('p').text(data.msg);
                        });
                    }
                }
                // 各种响应error处理-结束
                if ( AgentStateTime) {data.AgentStateTime = AgentStateTime}
                if (EventType) {
                    //同时将值传递出去
                    // alert(EventType)
                  console.log(EventType, CallDetailEvent, 88888)
                    phone.EventType = EventType;
                    phone.CallDetailEvent = CallDetailEvent;
                    // 这种条件情况不需要将状态改变 传递
                    // consulted 分为 区分
                    if (EventType === 'AgentStatus_Alerting' && (CallDetailEvent ==='CA_CALL_EVENT_ALERTING' || CallDetailEvent ==='CA_CALL_EVENT_CONSULT_ALERTING_TP')) {
                        console.log('呼入振铃----事件', window.phoneUserInfo.TerminalType, phone.config)
                        if (phone.config.autoAnswerCallInKey && phone.config.autoAnswerCallInKey == 'autoAnswerCallIn') {
                            // 坐席设置了呼入自动应答
                            phone.ucObj.doAnswer();
                        } else if (window.phoneUserInfo.TerminalType == '5') {
                            var local_audio_src = baseUrl + '/utils/Ringing.mp3';
                            var localAudio = document.getElementById('audio_local');
                            localAudio.src = local_audio_src;
                            localAudio.paused && (localAudio.play());
                            checkIsHiddenCalled(data.DNIS);
                        }
                    }
                    if (EventType === 'AgentStatus_Connected_Normal' && (CallDetailEvent === 'CA_CALL_EVENT_OUTBOUND_CONNECTED_OP' || CallDetailEvent === 'CA_CALL_EVENT_CONNECTED')) {
                        // 外呼/呼入接通时播放都提示
                        if (window.phoneUserInfo.TerminalType == '5') {
                            var local_audio_src = baseUrl + '/utils/Connected.mp3';
                            var localAudio = document.getElementById('audio_local');
                            localAudio.src = local_audio_src;
                            localAudio.paused && (localAudio.play());
                        }
                    }
                    if (EventType === 'AgentStatus_Otherwork' || EventType === 'AgentStatus_Consulted' || (EventType === 'AgentStatus_Connected_Normal' && CallDetailEvent === 'CA_CALL_EVENT_CONNECTED')) {
                        console.log('振铃结束咨询应答/其他状态--111111111--事件')
                        if (window.phoneUserInfo.TerminalType == '5') {
                            var localAudio = document.getElementById('audio_local');
                            console.log(localAudio.src)
                            if((localAudio.src && localAudio.src.indexOf('/utils/hangup.mp3') > 0) || (localAudio.src && localAudio.src.indexOf('/utils/Connected.mp3') > 0)) {
                                console.log('当前是挂掉/嘟铃声不处理')
                            } else {
                                var local_audio_src = '';
                                var localAudio = document.getElementById('audio_local');
                                localAudio.src = local_audio_src;
                                localAudio.pause();
                            }
                        }
                    }
                    if (EventType === 'AgentStatus_Disconnected' && (CallDetailEvent === 'CA_CALL_EVENT_OP_DISCONNECT' || CallDetailEvent === 'CA_CALL_EVENT_TP_DISCONNECT')) {
                      console.log('呼入振铃--挂断-------------事件', data);
                      if (window.phoneUserInfo.TerminalType == '5') {
                        var localAudio = document.getElementById('audio_local');
                        console.log(localAudio.src);
                        if(localAudio.src && localAudio.src.indexOf('/utils/hangup.mp3') > 0) {
                            console.log('当前是挂掉铃声不处理');
                        } else {
                            var disconnect_local_audio_src = baseUrl + '/utils/hangup.mp3';
                            localAudio.src = disconnect_local_audio_src;
                            localAudio.paused && (localAudio.play());
                        }
                      }
                    }
                    // 登录页进入后的首次登录置忙置闲处理
                    if (EventType === 'AgentStatus_Login') {
                        console.log('=======登录---电话loginsipstate')
                        autoplayFirstMute();
                        if(window.loginSipState) {
                            if(window.loginSipState === '在线') {
                                setTimeout(() => {
                                    console.log('登录后web电话设置置闲');
                                    phone.ucObj.doReady();
                                }, 1000);
                            } else {
                                setTimeout(() => {
                                    console.log('登录后web电话设置置忙');
                                    phone.ucObj.doNotReady();
                                }, 1000);
                            }
                        } else {
                            setTimeout(() => {
                                console.log('非登录页web电话进入需要置忙一下', phone.ucObj);
                                phone.ucObj.doNotReady();
                            }, 1000);
                        }
                    }
                    if (EventType === 'AgentStatus_Consulted' && CallDetailEvent === 'CA_CALL_EVENT_CONSULT_CONNECTED_TP') { // 咨询本方应答--会议置1
                        phone.customgetStateFn(new P.EventStatus(0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0), getStateTxt.call(phone,EventType,CallDetailEvent), data);
                        //phone.customgetStateFn(new P.EventStatus(0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,1,1,0,0,1), getStateTxt.call(phone,EventType,CallDetailEvent), data);
                        // 外呼振铃之后可挂断
                    } else if (EventType === 'AgentStatus_Connected_Normal' && CallDetailEvent === 'CA_CALL_EVENT_OUTBOUND_CONNECTED_TP') {
                        phone.agentCurrentCalled = 'TP' // 当前坐席通话状态内呼通话中
                        phone.customgetStateFn(new P.EventStatus(0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0), getStateTxt.call(phone,EventType,CallDetailEvent), data);
                    } else if (EventType === 'AgentStatus_Connected_Normal' && CallDetailEvent === 'CA_CALL_EVENT_OUTBOUND_CONNECTED_OP') {
                        phone.agentCurrentCalled = 'OP' // 当前坐席通话状态外呼通话中
                        phone.customgetStateFn(new P.EventStatus(0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,1,1,0,0,1), getStateTxt.call(phone,EventType,CallDetailEvent), data);
                    } else if (EventType === 'AgentStatus_Alerting' && CallDetailEvent === 'CA_CALL_EVENT_CONSULT_ALERTING_TP') { // 咨询本方振铃
                        phone.customgetStateFn(new P.EventStatus(0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1), getStateTxt.call(phone,EventType,CallDetailEvent), data);
                    } else if(EventType === 'AgentStatus_Connected_Normal' && CallDetailEvent === 'CA_CALL_EVENT_CONSULT_RETRIEVE'){//协作保持接回
                        phone.customgetStateFn(new P.EventStatus(0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,1), getStateTxt.call(phone,EventType,CallDetailEvent), data);
                    }
                    else {
                        phone.customgetStateFn(phone.config.eventList[EventType], getStateTxt.call(phone,EventType,CallDetailEvent), data);
                    }
                    // unknow 状态 进行 重新恢复
                    if (EventType === 'AgentStatus_Unkown') {
                        phone.agentCurrentCalled = null
                        phone.ucObj.GetAgentState(window.phoneUserInfo.agentID,function(res) {
                            if (res.Code === '0') {
                                phone.getEventStatus(res.Event);
                            }
                        })
                    }
                    //外呼本方振铃时 需手动调接听
                    if(CallDetailEvent === 'CA_CALL_EVENT_OUTBOUND_ALERTING_TP'){
                        // phone.ucObj.doAnswer();
                        phone.AlertScreenFn(data, 0);
                    }
                    //监听振铃需要调用接听接口
                    if(CallDetailEvent === 'CA_CALL_EVENT_MONITOR_ALERTING'){
                        phone.ucObj.doAnswer();
                    }
                    // 协作处理
                    if(CallDetailEvent === 'CA_CALL_EVENT_CONSULT_RETRIEVE'){
                        /*phone.ucObj.doGetAssociateData('SD',function(data){
                            console.log("CA_CALL_EVENT_CONSULT_RETRIEVE= " + data.Msg);
                            if(data.Msg.indexOf(";msg:")!==-1){
                                if(data.Msg.indexOf(";msg:true") > 0){
                                    alert("用户输入密码正确");
                                }else{
                                    alert("用户输入密码错误");
                                }
                            }
                        });*/
                    }

                    //设置相关操作
                    //呼入 呼出 振铃 设置坐席助手
                    if((EventType === 'AgentStatus_Alerting' && CallDetailEvent ==='CA_CALL_EVENT_ALERTING') || (EventType === 'AgentStatus_Connecting' && CallDetailEvent ==='CA_CALL_EVENT_OUTBOUND_ALERTING_OP')) {
                        //是否启动AI坐席助手
                        var autoAIHelpKey = phone.config.autoAIHelpKey;
                        if(autoAIHelpKey === 'autoAIHelp'){
                            // console.log('振铃的时候发送随路数据--Cmd_IContact_SetAssociateData')
                            // phone.ucObj.doSetCallData('SD','DetectSpeech')
                        }
                    }
                    //挂断后是否自动示忙
                    if(EventType === 'AgentStatus_Disconnected' && (CallDetailEvent ==='CA_CALL_EVENT_TP_DISCONNECT' || CallDetailEvent === 'CA_CALL_EVENT_OP_DISCONNECT')) {
                        phone.agentCurrentCalled = null;
                        if (acwTimer) {
                            clearTimeout(acwTimer);
                        }
                        var acwTimerKey = Number(phone.config.acwTimerKey);
                        console.log(acwTimerKey, acwTimerKey!='')
                        // if(acwTimerKey!=''&&acwTimerKey!=0){
                        if(acwTimerKey!='' || acwTimerKey== 0){
                            acwTimer = setTimeout(function() {
                                //是否自动置闲置忙
                                var autoReadyKey = phone.config.autoReadyKey;
                                if(autoReadyKey === 'autoNotReady'){
                                    console.log('置忙置闲notready', acwTimerKey*1000)
                                    phone.ucObj.doNotReady();
                                }else if(autoReadyKey === 'autoReady'){
                                    console.log('置忙置闲ready', acwTimerKey*1000)
                                    phone.ucObj.doReady();
                                }
                            }, acwTimerKey*1000);

                        }


                    }



                    // 随路数据
                    var m_IVRData = data.IVRData;
                    if (m_IVRData != null) {
                        if (m_IVRData.indexOf("cardNo")>0) {
                            var ivrDataList = m_IVRData.split("cardNo:");
                            console.log("随路数据_卡号: " + ivrDataList[1]);
                            data.IVRData = "随路数据_卡号: " + ivrDataList[1];
                        }
                    }

                    // 处理弹屏事件 外呼
                    if(EventType === 'AgentStatus_Connecting' && CallDetailEvent === 'CA_CALL_EVENT_OUTBOUND_ALERTING_OP'){
                        phone.AlertScreenFn(data, 0);
                    }
                    // 处理弹屏事件 内呼
                    if(EventType === 'AgentStatus_Alerting' && CallDetailEvent ==='CA_CALL_EVENT_ALERTING'){
                        phone.AlertScreenFn(data, 1);
                    }
                    // 咨询振铃弹屏处理(被咨询方事件)
                    if(EventType === 'AgentStatus_Alerting' && CallDetailEvent ==='CA_CALL_EVENT_CONSULT_ALERTING_TP') {
                        phone.AlertScreenFn(data, 1); // 被咨询方事件-tyy-0407-11:12
                        // phone.AlertScreenFn(data, 0); // 咨询方事件
                    }
                    // 挂断事件
                    if (EventType === 'AgentStatus_Disconnected') {
                        phone.AlertScreenFn(data, 2);
                        if (this && this.trigger) {
                            this.trigger('disconnected', data)
                        }
                    }
                }
                // 有可能返回值data.Result == 400 停止服务迁出
                var result = data.Result;
                if (result) {
                    phone.customgetStateFn(result)
                }
                phone.toEventType = EventType;
            }
        })
        /*
        * 暴露给用户的 API
        */
        _p(function (P, $){
            P.fn.defineRenderFn = function(loginingRender,loginRender,explicitNumRender,logoutRender, smallStatusRender) {
                var phone = this;
                if (loginingRender && (typeof loginingRender === 'function')){
                    phone.renderEvents.loginingRender = loginingRender;
                }
                if (loginRender && (typeof loginRender === 'function')){
                    phone.renderEvents.loginRender = loginRender;
                }
                if (explicitNumRender && (typeof explicitNumRender === 'function')){
                    phone.renderEvents.explicitNumRender = explicitNumRender;
                }
                if (logoutRender && (typeof logoutRender === 'function')){
                    phone.renderEvents.logoutRender = logoutRender;
                }
                if (smallStatusRender && (typeof smallStatusRender === 'function')){
                    phone.renderEvents.smallStatusRender = smallStatusRender;
                }
            }

            P.fn.create = function() {
                var phone = this;
                // 执行 addMenus 之前：
                // 允许用户通过修改 editor.menus 来自定义配置菜单
                // 因此要在 create 时执行，而不是 init
                phone.addAllMenus();
                // 创建 ucObj 对象
                //phone.ucObj = new P.UCObj(P.$window[0],P.$document[0]);
            }
            // 存储对接客户时，客户传入的方法，该方法带参数；
            // 每次states 改变 则执行该方法，将state传出
            P.fn.getStates = function(fn) {
                var phone = this;
                phone.customgetStateFn = fn; // 将参数传递出去
            }
            //弹屏处理
            P.fn.getAlertScreenFn = function(fn) {
                var phone = this;
                phone.AlertScreenFn = fn; // 将参数传递出去
            }

        })
        /*
        * 最终返回phone构造函数
        */
        return window.newPhone;
    })








